<?php
/**
 * Created by PhpStorm.
 * User: gem
 * Date: 2018/11/20
 * Time: 15:20
 */
namespace App\Repositorys;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Intervention\Image\ImageManagerStatic as Image;
use App\Http\Requests\StorePersonRequest;
use App\Http\Requests\UpdatePersonReuqest;
use App\Repositorys\BaseRepository;
use App\Person;

class PersonRepository
{
    use BaseRepository;

    protected $model;

    public function __construct(Person $person)
    {
        $this->model = $person;
    }

    /**
     * 导出Excel
     *
     * @param $request
     * @param $filter
     * @param $per_page
     * @param int $is_deleted
     * @return mixed
     */
    public function pageWithRequest($request, &$filter, &$per_page, $deleted_at = null)
    {
        // 获取查询参数
        $year = $request->input('year');
        $action = $request->input('action');
        $page = $request->input('page', 1);
        $per_page = $request->input('per_page', config('system.person.number'));
        $where = array(1, 2, 3);
        $keyword = $request->input('keyword');
        $is_the_city = $request->input('is_the_city', 'all');
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $five_saw_time = $request->input('five_saw_time', 'all');

        // 构造查询条件
        $person = clone $this->model;

        $person = $person->orderBy("id", "desc")->select('id', 'name', 'avatar', 'id_number', 'is_the_city', 'reg_addr', 'temp_addr', 'five_saw_time', 'phone');
        if ($year != '') {
            $person = $person->where('five_saw_time', '>=', strtotime("$year-01-01 00:00:00"));
            $person = $person->where('five_saw_time', '<=', strtotime("$year-12-31 23:59:59"));
        }
        if (!empty($start_time)) {
            $person = $person->where('five_saw_time', '>=', strtotime($start_time));
        }
        if (!empty($end_time)) {
            $person = $person->where('leave_time', '<=', strtotime($end_time));
        }
        if ($is_the_city !== 'all') {
            $person = $person->where('is_the_city', $is_the_city);
        }

        if ($five_saw_time !== 'all') {  // 是否还在本市
            if ($five_saw_time == '0') // 已离开
                $person = $person->where('five_saw_time', '=', 0);
            else                       // 在本市
                $person = $person->where('five_saw_time', '!=', 0);
        }

        // 搜索关键字(姓名，身份证和手机号码)
        if (! empty($keyword)) {
            $person = $person->whereRaw("(POSITION('$keyword' IN `name`)")
                             ->orWhereRaw("POSITION('$keyword' IN `id_number`)")
                             ->orWhereRaw("POSITION('$keyword' IN `phone`))");
        }
        // 是否是回收站
        if ($deleted_at == null) {
            $person = $person->whereNull('deleted_at');
        } else {
            $peron = $person->whereNotNull('deleted_at');
        }

        // 查询参数
        $filter = [
            'action' => $action,
            'keyword' => $keyword,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'is_the_city' => $is_the_city,
            'five_saw_time' => $five_saw_time,
            'page' => $page,
            'year' => $year
        ];
        unset($peron);

        return $person->paginate($per_page);
    }


    /**
     * 获取分页和参数
     *
     * @param $request
     * @param $filter
     * @param $per_page
     * @param int $is_deleted
     * @return mixed
     */
    public function excelWithRequest($request)
    {
        // 获取查询参数
        $year = $request->input('year');
        $action = $request->input('action');
        $page = $request->input('page', 1);
        $per_page = $request->input('per_page', config('system.person.number'));
        $where = array(1, 2, 3);
        $keyword = $request->input('keyword');
        $is_the_city = $request->input('is_the_city', 'all');
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $five_saw_time = $request->input('five_saw_time', 'all');

        // 构造查询条件
        $person = clone $this->model;

        $person = $person->orderBy("id", "desc")->select('id', 'name', 'avatar', 'id_number', 'is_the_city', 'reg_addr', 'temp_addr', 'five_saw_time', 'phone');
        if ($year != '') {
            $person = $person->where('five_saw_time', '>=', strtotime("$year-01-01 00:00:00"));
            $person = $person->where('five_saw_time', '<=', strtotime("$year-12-31 23:59:59"));
        }
        if (!empty($start_time)) {
            $person = $person->where('five_saw_time', '>=', strtotime($start_time));
        }
        if (!empty($end_time)) {
            $person = $person->where('leave_time', '<=', strtotime($end_time));
        }
        if ($is_the_city !== 'all') {
            $person = $person->where('is_the_city', $is_the_city);
        }

        if ($five_saw_time !== 'all') {  // 是否还在本市
            if ($five_saw_time == '0') // 已离开
                $person = $person->where('five_saw_time', '=', 0);
            else                       // 在本市
                $person = $person->where('five_saw_time', '!=', 0);
        }

        // 搜索关键字(姓名，身份证和手机号码)
        if (! empty($keyword)) {
            $person = $person->whereRaw("(POSITION('$keyword' IN `name`)")
                ->orWhereRaw("POSITION('$keyword' IN `id_number`)")
                ->orWhereRaw("POSITION('$keyword' IN `phone`))");
        }

        $person = $person->whereNull('deleted_at');


        $offset = $per_page * ($page - 1);

        $persons = $person->select('id', 'name', 'id_number', 'temp_addr', 'five_saw_time', 'phone')
            ->limit($per_page)
            ->offset($offset)
            ->get()->toArray();

        // 准备人员excel数据
        foreach ($persons as &$v) {
            if ($v['five_saw_time'] != 0)
                $v['five_saw_time'] = date("Y-m-d H:i:s", $v['five_saw_time']);
            else
                $v['five_saw_time'] = "已离开";

        }
        $first_id = $persons[0]['id'];
        $last_id = end($persons)['id'];
        $title = [['ID ', '姓名', '身份证号', '所在地', '到我市时间', '电话']];
        $persons = array_merge($title, $persons);

        // 生成Excel文件，并发送客户端
        \Excel::create('人员信息 ID ' . $first_id . '-' . $last_id, function ($excel) use ($persons) {
            $excel->sheet('persons', function ($sheet) use ($persons) {
                $sheet->rows($persons);
            });
        })->export('xls');
    }

    /**
     * 获取所有年份
     *
     * @return array
     */
    public function years()
    {
        $model = clone $this->model;
        $first = $model->orderBy("five_saw_time", "asc")
            ->select('five_saw_time')
            ->where('is_deleted', 0)
            ->where('five_saw_time', '!=', '')
            ->first();

        $model = $this->model;
        $last = $model->orderBy("five_saw_time", "desc")
            ->select('five_saw_time')
            ->where('is_deleted', 0)
            ->where('five_saw_time', '!=', '')
            ->first();

        $first_year = '';
        $last_year = '';
        if ($first) {
            $first_year = date('Y', $first->five_saw_time);
        }
        if ($last) {
            $last_year = date('Y', $last->five_saw_time);
        }
        $year_array = array();
        if ($first_year != '' && $last_year != '') {
            $count = $last_year - $first_year;
            for ($count; $first_year <= $last_year; $first_year++) {
                $year_array[] = (int)$first_year;
            }
        }

        unset($model);

        return $year_array;
    }

    /**
     * 保存人员信息
     *
     * @param StorePersonRequest $request
     */
    public function saveWithRequest(StorePersonRequest $request)
    {
        $image_path = '';

        if ($request->file('avatar')) {
            if ($request->file('avatar')->isValid()) {
                $avatar = '';
                $dir = 'fotoupload' . date('/Y/md/');
                $ext = '';
                try {
                    $file = $request->file('avatar');
                    $avatar = md5($file->getClientOriginalName() . time());
                    $ext = '.' . $file->getClientOriginalExtension();
                    $request->file('avatar')->move($dir, $avatar . $ext);
                    //Image::make($dir . $avatar . $ext)->resizeCanvas(150, 150)->save($dir . $avatar . '_150X150'. $ext);
                    Image::make($dir . $avatar . $ext)->fit(128, 182)->save($dir . $avatar . $ext);
                } catch (Illuminate\Filesystem\FileNotFoundException $e) {

                }
                $image_path = $dir . $avatar . $ext;
            }
        }

        $person = $this->model;

        $person->avatar = $image_path;
        $person->name = $request->input('name');
        $person->id_number = $request->input('id_number');
        $person->reg_addr = $request->input('reg_addr');
        $person->temp_addr = $request->input('temp_addr');
        $person->five_saw_time = strtotime($request->input('five_saw_time'));
        $person->leave_time = strtotime($request->input('leave_time'));
        $person->meet_situation = is_null($request->input('meet_situation')) ? '' : $request->input('meet_situation');
        $person->remark = is_null($request->input('remark')) ? '' : $request->input('remark');
        $person->is_the_city = $request->input('is_the_city');
        $person->phone = $request->input('phone');
        $person->qq = is_null($request->input('qq')) ? '' : $request->input('qq');
        $person->weixin = is_null($request->input('weixin')) ? '' : $request->input('weixin');
        $person->user_id = $request->user()->id;
        $person->meet_situation = mb_substr($person->meet_situation, 0, 255);
        $person->remark = htmlspecialchars($person->remark);

        $person->save();

        if ((! empty($person->leave_time)) && (! empty($person->five_saw_time))) {

            $person->times()->create([
                'five_saw_time' => $person->five_saw_time,
                'leave_time' => $person->leave_time,
            ]);
            $person->leave_time = 0;
            $person->five_saw_time = 0;
            $person->save();
        }
    }

    /**
     * 获取人员编辑页面信息
     *
     * @param $id
     * @return bool
     */
    public function getEditData($id)
    {

        $person = $this->getById($id);

        // 获取人员所在地
        $arr = ['', ''];
        $person->temp_addr2 = explode(",", $person->temp_addr);
        $person->temp_addr2 = array_merge($person->temp_addr2, $arr);

        // 获取人员户籍地址
        $person->reg_addr2 = explode(",", $person->reg_addr);
        $person->reg_addr2 = array_merge($person->reg_addr2, $arr);

        // 获取最后离开时间
        $person->min_time = $this->model->min_time();

        // 获取人员在本市时间列表，按时间倒序排列
        $times = array();
        foreach ($person->times as $v) {
            $times[] = $v;
        }
        $person->times = array_reverse($times);

        return $person;
    }

    /**
     * 更新人员信息
     *
     * @param UpdatePersonReuqest $request
     * @param Person $person
     */
    public function updateWithRequest(UpdatePersonReuqest $request, Person $person)
    {
        // 上传图片
        $image_path = '';
        if ($request->hasFile('avatar')) {
            if ($request->file('avatar')->isValid()) {
                $avatar = '';
                $dir = 'fotoupload' . date('/Y/md/');
                $ext = '';

                try {
                    $file = $request->file('avatar');
                    $avatar = md5($file->getClientOriginalName() . time());
                    $ext = '.' . $file->getClientOriginalExtension();
                    $request->file('avatar')->move($dir, $avatar . $ext);
                    //Image::make($dir . $avatar . $ext)->resize(150, 150)->save($dir . $avatar . $ext);
                    //Image::make($dir . $avatar . $ext)->resizeCanvas(128, 182)->save($dir . $avatar . $ext);
                    Image::make($dir . $avatar . $ext)->fit(128, 182)->save($dir . $avatar . $ext);
                } catch (Illuminate\Filesystem\FileNotFoundException $e) {

                }
                $image_path = $dir . $avatar . $ext;
            }
        }

        //  填充person对象数据
        if (! empty($image_path)) {
            $person->avatar = $image_path;
        }

        $person->name = $request->input('name');
        $person->id_number = $request->input('id_number');
        $person->reg_addr = $request->input('reg_addr');
        $person->temp_addr = $request->input('temp_addr');
        $person->five_saw_time = strtotime($request->input('five_saw_time'));
        $person->leave_time = strtotime($request->input('leave_time'));
        $person->meet_situation = is_null($request->input('meet_situation')) ? '' : $request->input('meet_situation');
        $person->remark = is_null($request->input('remark')) ? '' : $request->input('remark');
        $person->is_the_city = $request->input('is_the_city');
        $person->phone = $request->input('phone');
        $person->qq = is_null($request->input('qq')) ? '' : $request->input('qq');
        $person->weixin = is_null($request->input('weixin')) ? '' : $request->input('weixin');
        $person->user_id = $request->user()->id;
        $person->remark = addslashes($person->remark);
        $person->meet_situation = mb_substr($person->meet_situation, 0, 255);

        if (!empty($person->leave_time) && !empty($person->five_saw_time)) {
            $person->times()->create([
                'five_saw_time' => $person->five_saw_time,
                'leave_time' => $person->leave_time,
            ]);
            $person->leave_time = 0;
            $person->five_saw_time = 0;
        }

        $person->save();
    }

    /**
     * 从回收站彻底删除
     *
     * @param $ids
     * @return int
     */
    public function destroy($ids)
    {

        $arr = explode(',', $ids);
        if (count($arr) > 1) {
            return \App\Person::destroy($arr);
        }

        return $this->model->find($ids)->delete();
    }


    /**
     * 放入回收站
     *
     * @param $ids
     */
    public function recycle($ids)
    {
        $arr = explode(',', $ids);
        if (count($arr) > 1) {
            return \App\Person::softDelete($arr);
        }

        return $this->model->find($ids)->update(["deleted_at" => date('Y-m-d H:i:s')]);
    }


    /**
     * 从回收站还原
     *
     * @param Request $request
     */
    public function recover(Request $request)
    {
//        $id = $request->input('id', 0);
//        if ($id == 0) return ;
//
//        $this->model->find($id)->update(["deleted_at" => NULL]);
        $id = $request->input('id');
        if ($id)
            $id = explode(',', $id);
        else
            $id = '0';

        $data = DB::table('persons')->whereIn('id', $id)->update(["deleted_at" => NULL]);
    }


    /**
     * 切换是否本市
     *
     * @param Request $request
     */
    public function isCity(Request $request) : void
    {
        $id = $request->input('id', 0);
        $type = $request->input('type');
        if ($id == 0) return ;

        if ($type == 1) {
            $this->model->find($id)->update(["is_the_city" => 1]);
        } else {
            $this->model->find($id)->update(["is_the_city" => 0]);
        }
    }


}
